#include "verificationcode.h"
#include <QDateTime>
#include <cstdlib>  // 包含 srand 和 rand 函数
#include <ctime>    // 包含 time 函数

VerificationCode::VerificationCode(QWidget *parent)
    : QWidget(parent)
{
    // 设置固定大小
    setFixedSize(120, 50);

    // 初始化随机数种子
    srand(static_cast<unsigned int>(time(nullptr)));

    // 生成初始验证码
    generateNewCode();

    // 设置定时器用于动态效果
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, [this]() {
        update(); // 重绘
    });
    m_timer->start(300); // 每300毫秒更新一次

    // 设置鼠标样式
    setCursor(Qt::PointingHandCursor);
}

VerificationCode::~VerificationCode()
{
    if (m_timer) {
        m_timer->stop();
        delete m_timer;
    }
}

QString VerificationCode::getCode() const
{
    return m_code;
}

void VerificationCode::generateNewCode()
{
    m_code = generateCode(4);
    update(); // 重绘
}

QString VerificationCode::generateCode(int length)
{
    const QString chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
    QString result;

    for (int i = 0; i < length; ++i) {
        int index = rand() % chars.length();
        result.append(chars.at(index));
    }

    return result;
}

void VerificationCode::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    // 设置抗锯齿
    painter.setRenderHint(QPainter::Antialiasing, true);

    // 填充背景
    painter.fillRect(rect(), QColor(240, 240, 240));

    // 绘制干扰线
    for (int i = 0; i < 6; ++i) {
        painter.setPen(QColor(
            rand() % 170,
            rand() % 170,
            rand() % 170));

        int x1 = rand() % width();
        int y1 = rand() % height();
        int x2 = rand() % width();
        int y2 = rand() % height();

        painter.drawLine(x1, y1, x2, y2);
    }

    // 绘制干扰点
    for (int i = 0; i < 100; ++i) {
        painter.setPen(QColor(
            rand() % 255,
            rand() % 255,
            rand() % 255));

        painter.drawPoint(
            rand() % width(),
            rand() % height());
    }

    // 绘制验证码文本
    for (int i = 0; i < m_code.length(); ++i) {
        painter.setFont(QFont("Arial", 20 + rand() % 10, QFont::Bold));
        painter.setPen(QColor(
            rand() % 100,
            rand() % 100,
            rand() % 100));

        // 计算每个字符的位置，均匀分布
        int x = width() / m_code.length() * i + 10;
        int y = height() / 2 + 10 + rand() % 10 - 5;

        // 随机旋转角度
        painter.save();
        painter.translate(x, y);
        painter.rotate(-30 + rand() % 60);
        painter.drawText(0, 0, QString(m_code.at(i)));
        painter.restore();
    }
}

void VerificationCode::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        emit clicked();  // 发射点击信号
    }
    QWidget::mousePressEvent(event);
}
